package com.cafe.action.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.cafe.model.Customer;
import com.cafe.model.Order;
import com.cafe.model.OrderProduct;
import com.cafe.model.OrderState;
import com.cafe.model.Product;
import com.cafe.service.CustomerService;
import com.cafe.service.OrderService;
import com.cafe.service.ProductService;
import com.malamute.core.action.BaseAction;
import com.malamute.core.constant.SystemConstant;

/**
 * @description 前台用户
 * @version v1.0
 */
public class CustomerAction extends BaseAction {
	private Customer customer;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private ProductService productService;

	private String goPage;// 要跳转的页面

	private Order order;// 订单

	private List<OrderProduct> orderProducts;// 购物车中的商品

	private float cost;// 总金额

	public Customer getCustomer() {
		return customer;
	}

	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

	public void prepareForm() {
		setGoPage("customer/detail.jsp");
	}

	// 跳到个人信息修改页
	public String form() {
		if (customer != null) {
			customer = customerService.getCustomerById(customer.getId());
		}
		return SUCCESS;
	}

	// 修改成功后跳转页面
	public void prepareUpdate() {
		setGoPage("customer/detail.jsp?isOk=true");
	}

	// 修改个人信息
	public String update() {
		Customer changed = customerService.getCustomerById(customer.getId());
		changed.setName(customer.getName());
		changed.setPassword(customer.getPassword());
		changed.setBirthday(customer.getBirthday());
		changed.setEmail(customer.getEmail());
		changed.setMobilePhone(customer.getMobilePhone());
		customerService.updateCustomer(changed);
		return SUCCESS;
	}

	public void prepareShopCartDetail() {
		setGoPage("customer/shopcart.jsp");
	}

	// 购物车详细
	public String shopCartDetail() {
		this.loadCookie();
		return SUCCESS;
	}

	public void prepareOrder() {
		setGoPage("customer/order_success.jsp");
	}

	// 下订单
	public String order() {
		this.loadCookie();
		loadCustomerFromSession();
		order.setSerialNum("O_" + System.currentTimeMillis());
		order.setOrderProducts(orderProducts);
		for (OrderProduct op : orderProducts) {
			op.setOrder(order);
		}
		order.setCustomer(customer);
		orderService.saveOrder(order);

		this.deleteShopCartCookie();
		return SUCCESS;
	}

	public void prepareConfirm() {
		setGoPage("customer/confirm_order.jsp");
	}

	public String confirm() {
		this.loadCookie();
		return SUCCESS;
	}

	// 从cookie中获购物车中的信息
	private void loadCookie() {
		// (cookie.getName());// product1
		// (cookie.getValue());// 份数
		Cookie[] cookies = request.getCookies();
		Integer[] ids = new Integer[cookies.length - 1];
		Map idPieceMap = new HashMap();
		int j = 0;
		boolean hasSelectProduct = false;
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if (cookie.getName().indexOf("product") != -1) {
				hasSelectProduct = true;
				int productId = Integer.parseInt(cookie.getName().substring(
						"product".length()));
				ids[j++] = productId;
				idPieceMap.put(productId, Integer.parseInt(cookie.getValue()));
			}
		}
		// 获取商品
		if (hasSelectProduct) {

			DetachedCriteria criteria = DetachedCriteria
					.forClass(Product.class);
			criteria.add(Restrictions.in("id", ids));
			List<Product> products = productService.listProductsByIds(criteria);
			orderProducts = new ArrayList();
			for (Product tmp : products) {
				OrderProduct orderProduct = new OrderProduct();
				orderProduct.setProduct(tmp);
				orderProduct.setPiece((Integer) idPieceMap.get(tmp.getId()));
				// 金额计算
				cost += orderProduct.getPiece()
						* orderProduct.getProduct().getPrice();
				orderProducts.add(orderProduct);
			}
		}
	}

	private void loadCustomerFromSession() {
		String customerIdSaveStr = (String) session
				.get(SystemConstant.SES_CUSTOMER_LOGIN);
		String custoerIdStr = customerIdSaveStr
				.substring(SystemConstant.SES_PREFIX_CUSTOMER.length());
		int customerId = Integer.parseInt(custoerIdStr);
		this.customer = customerService.getCustomerById(customerId);
	}

	// 创建完后删除cookie
	private void deleteShopCartCookie() {
		Cookie[] cookies = request.getCookies();
		try {
			for (int i = 0; i < cookies.length; i++) {
				Cookie tmp = cookies[i];
				tmp.setMaxAge(0);
				tmp.setPath("/malamute/web/");// 根据你创建cookie的路径进行填写
				response.addCookie(tmp);
			}
		} catch (Exception ex) {

		}
	}

	public void prepareListOrders() {
		setGoPage("customer/customer_order_list.jsp");
	}

	// 显示所有已建订单
	public String listOrders() {
		this.loadCustomerFromSession();
		DetachedCriteria criteria = DetachedCriteria.forClass(Order.class);
		criteria.add(Restrictions.eq("customer", customer));
		orderService.listOrdersByPage(criteria, page);
		return SUCCESS;
	}

	public String confirmOrder() {
		if (order != null) {
			order = orderService.getOrderById(order.getId());
			order.setState(OrderState.SUCCESS);
			order.setModifyTime(new Date());
			orderService.updateOrder(order);
		}
		return ACTION;
	}

	public void prepareViewOrder() {
		setGoPage("customer/order_detail.jsp");
	}

	// 查看订单
	public String viewOrder() {
		if (order != null) {
			order = orderService.getOrderById(order.getId());
		}
		return SUCCESS;
	}

	// 定桌位
	public String book() {
		return SUCCESS;
	}

	// 结帐
	public String pay() {
		return null;
	}

	public String getGoPage() {
		return goPage;
	}

	public void setGoPage(String goPage) {
		this.goPage = goPage;
	}

	public Order getOrder() {
		return order;
	}

	public void setOrder(Order order) {
		this.order = order;
	}

	public List getOrderProducts() {
		return orderProducts;
	}

	public void setOrderProucts(List orderProducts) {
		this.orderProducts = orderProducts;
	}

	public float getCost() {
		return cost;
	}

	public void setCost(float cost) {
		this.cost = cost;
	}

}
